import * as step from '@flow-step/step-toolkit'
import * as path from 'path'
import process from 'process'
import axios from 'axios'

export async function getOssEndpoint() {
    let endpoint = `https://oss-${process.env.OSS_REGION as string}-internal.aliyuncs.com`
    try {
        await axios.get(`${endpoint}`, {timeout: 1000})
    } catch (error) {
        // @ts-ignore
        if (!(error.status && error.status == 403)) {
            step.info('OSS internal network address is unreachable, using OSS public network address instead. ')
            endpoint = `https://oss-${process.env.OSS_REGION as string}.aliyuncs.com`
        }
    }
    return endpoint
}

export async function download() {

    const targetPath = process.env.TARGET_PATH as string || ""
    const projectDir = process.env.PROJECT_DIR as string
    let localPath = path.join(projectDir, targetPath)
    const ossPath = process.env.OSS_PATH || ""
    if (!localPath.endsWith('/')){
        localPath = localPath + '/'
    }

    // get oss certificate
    const flowJobToken: string | undefined =
        process.env['FLOW_JOB_TOKEN']
    if (flowJobToken == undefined) {
        throw new Error('missing FLOW_JOB_TOKEN')
    }
    const OssRamCertificate = await step.certificate.getOssRamServiceConnectionCertificate(flowJobToken,process.env.SERVICE_CONNECTION_ID as string)
    if (OssRamCertificate == undefined || OssRamCertificate.accessKeyId == undefined) {
        throw new Error(`got OssRamServiceConnectionCertificate but error: ${JSON.stringify(OssRamCertificate)}`)
    }
    let endpoint = await getOssEndpoint()
    const accessKeyID = OssRamCertificate.accessKeyId;
    const accessKeySecret = OssRamCertificate.accessKeySecret;
    const securityToken = OssRamCertificate.securityToken;
    const bucket = process.env.OSS_BUCKET as string;

    step.info(`ossutil cp -r oss://${bucket}/${ossPath} ${localPath} --update -e ${endpoint} `)
    //ensure dirs are also downloaded
    const resultCode = await step.exec.call('ossutil', ['cp','-r', `oss://${bucket}/${ossPath}`, localPath,  '--update', '-i', accessKeyID, '-k', accessKeySecret, '-t', securityToken, '-e', endpoint, '--retry-times', '3'],{
        listener: {
            stdoutLine: (line: string) => step.info(line),
            stderrLine: (line: string) => step.error(line)
        }
    })
    if (resultCode != 0) {
        throw new Error(`download failed, exit code ${resultCode}`)
    }

    const OSS_BUCKET_URL = `https://oss.console.aliyun.com/bucket/oss-${process.env.OSS_REGION as string}/${bucket}/object`
    step.info(`OSS_BUCKET_URL=${OSS_BUCKET_URL}`)

    if (process.env.PIPELINE_LOCALE == 'zh_CN'){
        step.interaction.addLink('下载地址', OSS_BUCKET_URL)
    }else{
        step.interaction.addLink('Download Address', OSS_BUCKET_URL)
    }
}